package com.zegoto.design.design.behavior.state;

// 定义电梯状态接口
interface ElevatorState {
    void openDoor();
    void closeDoor();
    void moveTo(int floor);
}

// 具体的电梯状态类
class ClosedState implements ElevatorState {
    private Elevator elevator;

    public ClosedState(Elevator elevator) {
        this.elevator = elevator;
    }

    public void openDoor() {
        System.out.println("电梯门打开了");
        elevator.changeState(new OpenedState(elevator));
    }

    public void closeDoor() {
        System.out.println("电梯门已经关闭了");
    }

    public void moveTo(int floor) {
        System.out.println("电梯已经在运行中，请等待到达目标楼层");
    }
}

class OpenedState implements ElevatorState {
    private Elevator elevator;

    public OpenedState(Elevator elevator) {
        this.elevator = elevator;
    }

    public void openDoor() {
        System.out.println("电梯门已经打开了");
    }

    public void closeDoor() {
        System.out.println("电梯门关闭了");
        elevator.changeState(new ClosedState(elevator));
    }

    public void moveTo(int floor) {
        System.out.println("请先关闭电梯门再选择楼层");
    }
}

// 上下文类
class Elevator {
    private ElevatorState state;
    private int currentFloor;

    public Elevator() {
        state = new ClosedState(this);
        currentFloor = 1;
    }

    public void changeState(ElevatorState state) {
        this.state = state;
    }

    public void openDoor() {
        state.openDoor();
    }

    public void closeDoor() {
        state.closeDoor();
    }

    public void moveTo(int floor) {
        state.moveTo(floor);
        currentFloor = floor;
        System.out.println("电梯到达了第" + currentFloor + "层楼");
    }
}

public class StateDemo {

    public static void main(String[] args) {
        Elevator elevator = new Elevator();

        // 关门状态
        elevator.closeDoor();
        // 电梯门打开
        elevator.openDoor();
        // 电梯门关闭
        elevator.closeDoor();
        // 电梯上行到3楼
        elevator.moveTo(3);
        // 电梯再次开门
        elevator.openDoor();
        // 电梯关门
        elevator.closeDoor();
        // 电梯下行到1楼
        elevator.moveTo(1);
    }

}
